package com.project.controller;

import com.project.biz.RedisBiz;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @Description: 图片验证码
 * @Author: zhuchi
 * @CreateDate: 2020/8/13 23:06
 * @Version: 1.0
 */
@Api(value = "ImgCodeController", description = "图片验证码")
@Slf4j
@RestController
public class ImgCodeController {

    /**
     * 用户缓存信息
     */
    @Autowired
    private RedisBiz redisBiz;

    /**
     * 获取图片验证码
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/imgCode")
    public void imgCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //获取注册令牌
        String registerKey = request.getParameter("registerKey");
        response.setContentType("image/gif");
        //  创建画布
        int width = 90;
        int height = 35;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //  获得画笔
        Graphics g = bufferedImage.getGraphics();
        //  填充背景颜色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        //  绘制边框
        g.setColor(Color.WHITE);
        g.drawRect(0, 0, width-2, height-2);
        //  准备随机对象
        Random r = new Random();
        //  准备数据
        String data = "abcdefghijklmnopqrstuvwxyz1234567890";
        //  生成验证码
        String code = "";
        //  书写4个随机字符
        for (int i = 0; i < 4; i++) {
            //  设置字体
            g.setFont(new Font("宋体", Font.BOLD, 24));
            //  设置随机颜色
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            String str = data.charAt(r.nextInt(data.length())) + "";
            g.drawString(str, 10 + i * 18, 22);
            code = code + str;
        }
        //  绘制干扰线
        for (int i = 0; i < 8; i++) {
            //  设置随机颜色
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }

        if (StringUtils.isNotBlank(registerKey)){
            //将注册令牌和图形验证发放入Redis
            this.redisBiz.setRegisterImgCode(registerKey, code);
        }
        //  将画布显示在浏览器中
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }

}
